import React, { useState, useEffect } from 'react';
import {
  Box,
  Paper,
  Typography,
  ToggleButtonGroup,
  ToggleButton,
  CircularProgress,
  Alert,
  Divider,
  TextField
} from '@mui/material';
import ReactECharts from 'echarts-for-react';
import { QueryResponse, ChartType } from '@/types';
import { generateChartConfig } from '@/api/apiClient';

const CHART_TYPES: Array<{ value: ChartType; label: string }> = [
  { value: 'bar', label: '柱状图' },
  { value: 'line', label: '折线图' },
  { value: 'pie', label: '饼图' }
];

interface ChartDisplayProps {
  queryResult: QueryResponse | null;
}

const ChartDisplay: React.FC<ChartDisplayProps> = ({ queryResult }) => {
  const [chartType, setChartType] = useState<ChartType | null>(null);
  const [chartConfig, setChartConfig] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleChartTypeChange = async (
    _event: React.MouseEvent<HTMLElement>,
    newChartType: ChartType | null
  ) => {
    if (!newChartType || !queryResult) return;
    
    setChartType(newChartType);
    setLoading(true);
    setError(null);
    
    try {

      const newConfig = await generateChartConfig(
        queryResult.data,
        queryResult.sql,
        newChartType
      );
      
      setChartConfig(newConfig);
    } catch (err) {
      setError(err instanceof Error ? err.message : '生成图表时出错');
    } finally {
      setLoading(false);
    }
  };


  if (!queryResult) {
    return null;
  }


  useEffect(() => {

    if (queryResult.chart_config) {
      setChartConfig(queryResult.chart_config);

      setChartType(queryResult.chart_config.series?.[0]?.type as ChartType || 'bar');
    } else {

      setChartConfig(null);
      setChartType(null);
    }
  }, [queryResult]);

  return (
    <Paper elevation={3} sx={{ p: 3, my: 3 }}>
      <Typography variant="h6" gutterBottom>
        查询结果可视化
      </Typography>
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle2" gutterBottom>
          选择图表类型
        </Typography>
        <ToggleButtonGroup
          value={chartType}
          exclusive
          onChange={handleChartTypeChange}
          aria-label="chart type"
        >
          {CHART_TYPES.map((type) => (
            <ToggleButton key={type.value} value={type.value} aria-label={type.label}>
              {type.label}
            </ToggleButton>
          ))}
        </ToggleButtonGroup>
      </Box>
      
      
      {error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}
      
      
      {loading && (
        <Box sx={{ display: 'flex', justifyContent: 'center', my: 4 }}>
          <CircularProgress />
        </Box>
      )}
      
      
      {!loading && chartConfig && (
        <Box sx={{ height: 400, mt: 2 }}>
          <ReactECharts
            option={chartConfig}
            style={{ height: '100%', width: '100%' }}
            opts={{ renderer: 'canvas' }}
          />
        </Box>
      )}
      
      <Divider sx={{ my: 3 }} />
      
      <Box>
        <Typography variant="subtitle2" gutterBottom>
          生成的SQL查询
        </Typography>
        <TextField
          fullWidth
          multiline
          rows={10}
          variant="outlined"
          value={queryResult.sql}
          InputProps={{
            readOnly: true,
          }}
          sx={{ mb: 2, fontFamily: 'monospace' }}
        />
        
      </Box>
    </Paper>
  );
};

export default ChartDisplay;